from flask import current_app
from flask import redirect
from flask import render_template, jsonify,g
from flask import request
from info import constants
from info import db
from info.models import User, Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu

@profile_blu.route('/news_list')
@user_login_data
def user_news_list():
    page = request.args.get("p", 1)
    user = g.user
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginates = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginates.items
        current_page = paginates.page
        total_page = paginates.pages
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "current_page":current_page,
        "total_page":total_page,
        "news_list":news_dict_li
    }

    return render_template('news/user_news_list.html',data=data)

@profile_blu.route('/news_release',methods=["POST","GET"])
@user_login_data
def news_release():
    # 加载新闻分类
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        category_dict_li.pop(0)

        return render_template('news/user_news_release.html',data={"categories":category_dict_li })

    # 获取参数
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)

    # 取到图片，并把图片传到七牛云上
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)


    # 初始化新闻模型
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 代表待审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")
    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/collection', methods=["POST","GET"])
@user_login_data
def user_collection():
    # 获取参数
    page = request.args.get("p", 1)
    # 校验
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 获取用户指定收藏的新闻
    user = g.user
    total_page = 1
    current_page = 1
    news_list = []
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)

        # 当前页数
        current_page = paginate.page
        # 总页数
        totle_page = paginate.pages
        # 每页数据
        news_list = paginate.items
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_dict())

    data = {
        "current_page": current_page,
        "totle_page": totle_page,
        "collections": news_dict_li
    }
    return render_template('news/user_collection.html',data=data)

@profile_blu.route('/pass_info', methods=["POST","GET"])
@user_login_data
def pass_info():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 获取当前登录用户的信息
    user = g.user

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 更新数据
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route('/pic_info', methods=["POST","GET"])
@user_login_data
def pic_info():

    if request.method == 'GET':
        return render_template('news/user_pic_info.html',data=g.user.to_dict())

    # 上传头像（取到上传的图像）
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        key = storage(avatar)
    except Exception as e:
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像错误")
    # 保存头像地址
    g.user.avatar_url = key

    return jsonify(errno=RET.OK, errmsg="OK",data={"avatar_url": constants.QINIU_DOMIN_PREFIX+key})


@profile_blu.route('/base_info',methods=["POST","GET"])
@user_login_data
def base_info():
    if request.method == "GET":
        return render_template('news/user_base_info.html',data=g.user.to_dict())

    # 修改用户数据
    # 1.获取用户数据
    user = g.user
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2.校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.初始化用户模型
    user = User()
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    # try:
    #     db.session.add(User())
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    #     db.session.rollback()
    #     return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user": user.to_dict() if user else None
            }
    return render_template('news/user.html',data=data)
